package com.suredy.app.porject.ctrl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.suredy.app.porject.constants.ContractStatus;
import com.suredy.app.porject.constants.ContractType;
import com.suredy.app.porject.constants.MoneyType;
import com.suredy.app.porject.model.Contract;
import com.suredy.app.porject.service.ContractSrv;
import com.suredy.core.ctrl.BaseCtrl;
import com.suredy.core.mvc.model.MessageModel;

/**
 * 财务功能视图控制器
 * 
 * @author VIVID.G
 * @since 2016-7-27
 * @version v0.1
 */
@Controller
@RequestMapping("/cw")
public class CWCtrl extends BaseCtrl {

	@Autowired
	private ContractSrv contractSrv;

	/**
	 * 待确认完工结算合同列表
	 * 
	 * @return
	 */
	@RequestMapping(value = "/for-clearing-confirm")
	public String listForClearingConfirm(String cNo, String cName, Boolean confirm, Integer page, Integer pageSize, Model model) {
		String view = "app/cw/for-clearing-confirm";

		if (page == null || page < 1)
			page = 1;

		if (pageSize == null || pageSize < 1)
			pageSize = 30;

		DetachedCriteria dc = this.contractSrv.getDc(null);

		dc.add(Restrictions.in("type", ContractType.MAIN_CONTRACT_TYPES)); // 主合同
		dc.add(Restrictions.eq("status", ContractStatus.COMPLETED)); // 完成结算
		// dc.add(Restrictions.or(Restrictions.isNull("finishConfirm"),
		// Restrictions.eq("finishConfirm", false))); // 未确认

		if (!StringUtils.isBlank(cNo)) {
			dc.add(Restrictions.like("no", cNo, MatchMode.ANYWHERE));
		}

		if (!StringUtils.isBlank(cName)) {
			dc.add(Restrictions.like("name", cName, MatchMode.ANYWHERE));
		}

		if (confirm != null) {
			if (confirm) {
				dc.add(Restrictions.eq("finishConfirm", true));
			} else {
				dc.add(Restrictions.or(Restrictions.isNull("finishConfirm"), Restrictions.eq("finishConfirm", false)));
			}
		}

		dc.addOrder(Order.asc("finishConfirm"));
		dc.addOrder(Order.asc("no"));

		@SuppressWarnings("unchecked")
		List<Contract> data = (List<Contract>) this.contractSrv.readPageByCriteria(dc, page, pageSize);

		model.addAttribute("data", data);
		model.addAttribute("cNo", cNo);
		model.addAttribute("cName", cName);
		model.addAttribute("confirm", confirm);
		model.addAttribute("page", page);
		model.addAttribute("pageSize", pageSize);
		model.addAttribute("count", this.contractSrv.getCountByCriteria(dc));

		return view;
	}

	@RequestMapping(value = "/confirm-clearing/{id}", method = RequestMethod.POST)
	@ResponseBody
	public Object confirmClearing(@PathVariable String id) {
		if (StringUtils.isBlank(id))
			return MessageModel.createErrorMessage("确认信息无效！", null);

		String ql = "UPDATE Contract T SET T.finishConfirm = ? WHERE T.id = ?";

		int count = this.contractSrv.updateByQL(ql, true, id);

		if (count != 1)
			return MessageModel.createErrorMessage("确认失败！", null);

		return MessageModel.createSuccessMessage("操作成功！", null);
	}

	/**
	 * 待确认成本费用列表
	 * 
	 * @return
	 */
	@RequestMapping(value = "/for-payout-confirm")
	public String listForPayoutConfirm(String cNo, String cName, String mSource, Boolean confirm, Integer page, Integer pageSize, Model model) {
		String view = "app/cw/for-payout-confirm";

		if (page == null || page < 1)
			page = 1;

		if (pageSize == null || pageSize < 1)
			pageSize = 30;

		String where = "WHERE T.payOut = ? AND T.name IN ({:NAME})";

		List<Object> params = new ArrayList<Object>();

		params.add(true);

		String tmp = "";
		for (MoneyType type : MoneyType.FOR_BID_PAYOUT) {
			if (!StringUtils.isBlank(tmp))
				tmp += ",";

			tmp += "?";

			params.add(type.getValue());
		}

		where = where.replace("{:NAME}", tmp);

		if (!StringUtils.isBlank(cNo)) {
			where += " AND C.no LIKE ?";

			params.add("%" + cNo.trim() + "%");
		}

		if (!StringUtils.isBlank(cName)) {
			where += " AND C.name LIKE ?";

			params.add("%" + cName.trim() + "%");
		}

		if (!StringUtils.isBlank(mSource)) {
			where += " AND T.source LIKE ?";

			params.add("%" + mSource.trim() + "%");
		}

		if (confirm != null) {
			if (confirm)
				where += "AND T.cwConfirm = ?";
			else
				where += "AND (T.cwConfirm IS NULL or T.cwConfirm = ?)";

			params.add(confirm);
		}

		String ql = "SELECT T.name, T.time, T.total, T.remark, C.name, C.type, C.companyA, C.companyB, C.id, T.id, C.no, T.source, T.cwConfirm FROM ContractMoney T LEFT JOIN T.contract C " + where + " ORDER BY T.cwConfirm, C.no, T.time, CONVERT_GBK(T.name)";

		List<?> data = this.contractSrv.readPageByQL(ql, page, pageSize, params.toArray());

		ql = "SELECT COUNT(T.id) FROM ContractMoney T LEFT JOIN T.contract C " + where;

		model.addAttribute("data", data);
		model.addAttribute("cNo", cNo);
		model.addAttribute("cName", cName);
		model.addAttribute("mSource", mSource);
		model.addAttribute("confirm", confirm);
		model.addAttribute("page", page);
		model.addAttribute("pageSize", pageSize);
		model.addAttribute("count", this.contractSrv.getCountByQL(ql, params.toArray()));

		return view;
	}

	@RequestMapping(value = "/confirm-payout/{id}", method = RequestMethod.POST)
	@ResponseBody
	public Object confirmPayout(@PathVariable String id) {
		if (StringUtils.isBlank(id))
			return MessageModel.createErrorMessage("确认信息无效！", null);

		String ql = "UPDATE ContractMoney T SET T.cwConfirm = ? WHERE T.id = ?";

		int count = this.contractSrv.updateByQL(ql, true, id);

		if (count != 1)
			return MessageModel.createErrorMessage("确认失败！", null);

		return MessageModel.createSuccessMessage("操作成功！", null);
	}
}
